// import {  worker } from 'workerpool'
import Mustache from 'mustache'
import { lookup } from '@/mustache/customize.js'
import _ from 'lodash'
import { regStrToNum } from '@/utils/LodashUtils.js'
import { hasMustache } from '@/utils/MustacheUtils.js'

/**
 * 主要逻辑: 渲染sheet
 * @param newSheet
 * @param data
 * @param fnArr
 */
// export const renderView = async (newSheet, data, fnMap) => {
export const renderView = async (newSheet, data, fnArr) => {
  // console.log('renderView')

  // !!!因为使用了Promise, 这里无法使用动态import!!!
  // const Mustache = await import('https://cdn.jsdelivr.net/npm/mustache@4.2.0/mustache.mjs');

  await setData(data, fnArr)

  // console.log('newSheet', newSheet)

  data.tempSheet = newSheet

  Mustache.Context.prototype.lookup = lookup
  // console.log('rowCount', newSheet.getRowCount())
  // console.log('columnCount', newSheet.getColumnCount())
  for (let rowNumber = 0; rowNumber < newSheet.getRowCount(); rowNumber++) {
    for (let colNumber = 0; colNumber < newSheet.getColumnCount(); colNumber++) {
      data.curRC = { r: rowNumber, c: colNumber }
      const cellValue = _.toString(newSheet.getValue(rowNumber, colNumber))
      if (hasMustache(cellValue)) {
        // console.log('cellValue = ' + cellValue)
        // console.log('rowNumber = ' + rowNumber)
        // console.log('colNumber = ' + colNumber)
        try {
          const result = regStrToNum(Mustache.render(cellValue, data))
          // console.log('result = ' + result)
          if (result) {
            newSheet.setValue(rowNumber, colNumber, result)
          }
        } catch (e) {
          console.log('render', e)
          throw e
        }
      }
    }
  }
}

// const setData = async (data, fnMap) => {
//   for (let [jsPath, fnList] of fnMap) {
//     const module = await loadModule(jsPath)
//     if (fnList) {
//       for (let fnName of fnList) {
//         const fn = module[fnName]
//         if (fn) {
//           await fn.call(null, data)
//         }
//       }
//     }
//   }
// }

const setData = async (data, fnArr) => {
  if (fnArr && fnArr.length > 0) {
    for (let fn of fnArr) {
      if (fn) {
        await fn.call(null, data)
      }
    }
  }
}

// const moduleCache = new Map()
// const loadModule = async (path) => {
//   if (!moduleCache.has(path)) {
//     moduleCache.set(path, await import(path))
//   }
//   return moduleCache.get(path)
// }

// worker({ renderView })
